<template>
  <div class="w-[100%] h-[100%] flex-center">
    <div class="absolute top-[0] left-[0]">
      <el-button round class="mb-4" @click="handleBtnClick({type:'back'})">
        <Icon icon="tabler:arrow-back-up"/>
        返回
      </el-button>
    </div>


    <div>
      <div class="flex items-center">
        <div class="w-[26px] h-[26px] bg mr-[10px]"
             style="background-image: url(https://img.alicdn.com/imgextra/i3/801089336/O1CN01w8cwfq2IpwkMyVMy2_!!801089336.png)"></div>
        订单已提交，请于{{ getTwoNum(Math.floor(time / 60)) }}分{{ getTwoNum(time % 60) }}秒完成支付 {{  app.payStatus }}
        <span
          class="text-[#666666] text-[12px]">（逾期订单将被取消）</span>
      </div>

      <div class="text-[#999999] flex-center mt-[25px]">
        <div>订单编号：{{ orderInfo.no }}</div>
        <div class="ml-[30px] text-[#3721FF]">共{{
            selectedPackage.packageCount || 0
          }}个席位>>
        </div>
      </div>

      <div class="flex-center mt-[60px]">应付金额：<span
        class="text-[#FF731A] text-[18px]">￥{{ selectedPackage.discountPrice || 0 }}</span></div>

      <div class="flex-center mt-[25px]">支付方式：

        <el-radio-group v-model="selectedMethod">
          <!-- works when >=2.6.0, recommended ✔️ not work when <2.6.0 ❌ -->
          <el-radio :value="item.code"
                    v-for="(item,index) in method"
                    :key="index"
          >
            <div class="w-[30px] h-[30px] bg" :style="`background-image:url(${ item.url })`">

            </div>
          </el-radio>

        </el-radio-group>

      </div>


      <div class="barCode flex-center mt-[60px]">
        <div class="w-[173px] h-[169px] bg flex-center"
             style="background-image: url(https://img.alicdn.com/imgextra/i2/801089336/O1CN014SqpjN2IpwkMs2hOa_!!801089336.png)">
          <div class="w-[149px] h-[150px] ">
            <canvas :id="ctxId" v-style="`width: 150px;height:150px;`" class=""
            >

            </canvas>

          </div>
        </div>
      </div>

      <div class="mt-[60px] flex-center">
        使用{{
          method.find(at => {
            return at.code == selectedMethod
          })?.name
        }}APP扫码完成后支付
      </div>


      <div class="flex-center mt-[15px]">
        <el-button @click="getQrCode">刷新二维码</el-button>

        <el-button type="primary" @click="handleBtnClick({type:'success'})">支付成功</el-button>

      </div>
    </div>




  </div>
</template>
<script setup lang="ts">

import {getOrderDetail} from "@/api/pay/order";
import {useAppStore} from "@/store/modules/app";
import {useMessage} from "@/hooks/web/useMessage";

const app = useAppStore();
import CheckPay from "./checkPay.vue"

import QRCode from 'qrcode';

const ctxId=ref(`ctx${ + new Date() }`)

const ConfirmPropsRef=ref(null)


import {DICT_TYPE, getStrDictOptions} from "@/utils/dict";

const channelType = getStrDictOptions(DICT_TYPE.PAY_CHANNEL_CODE);


import {getTwoNum} from "@/utils";
import router from "@/router";

import {FeeApi} from "@/api/fee";
import InfoAction from "@/views/logistics/remoteArea/components/InfoAction.vue";
import dayjs from "dayjs";

const props = defineProps({
  orderInfo: {
    type: Object,
    required: false,
    default: () => {
    }
  },
  selectedPackage: {
    type: Object,
    required: false,
    default: () => {
    }
  }
})

let timer;

let time = ref(3 * 60)

const back = inject<() => void>('back');


const emit = defineEmits(['execute'])

const submitInfo = ref({})

const method = ref([
  {
    name: "微信",
    url: "https://img.alicdn.com/imgextra/i3/801089336/O1CN01uLMQLc2IpwkBoslCg_!!801089336.png",
    code: "wechat",
    code1: "wx_native"
  },
  {
    name: "支付宝",
    url: "https://img.alicdn.com/imgextra/i2/801089336/O1CN01PqY72i2Ipwk56JFFD_!!801089336.png",
    code: "alipay",
    code1: "alipay_qr"
  }
])

const selectedMethod = ref("wechat")

const handleBtnClick = (e) => {
  let type = e.type;
  try {
    fn[type](e)
  } catch (e) {
    console.log(`${type}不为空`)
  }
}

const fn = {
  back() {
    back();
  },
  async success(){
    console.log(props.orderInfo)
    let res = await  getOrderDetail(props.orderInfo.payOrderId);
    //已支付
    if(res.status == 10){
      sessionStorage.setItem('payInfo',JSON.stringify(generateInfo()))
      app.payStatus=false;
      router.push(`/fee/fee/paid`);
    }else{
      useMessage().error('暂无支付信息')
      getQrCode();
    }
  }
}

const initTimer = () => {
  clearInterval(timer)
  timer = setInterval(() => {

    let t = time.value;

    console.log(t)
    t--;
    if (t < 0) {
      t = 0
    }

    if (t == 0) {
      //时间到了返回上一页
      clearInterval(timer);
      back();
    }

    time.value = t;

  }, 1000)
}

//获取二维码
const getQrCode = async () => {
  time.value= 3 * 60;
  let res = await FeeApi.submitOrder({
    channelCode: method.value.find(at => at.code == selectedMethod.value)?.code1,
    returnUrl: "https://blog.csdn.net/xiao_qiang666/article/details/148592009",
    id: props.orderInfo.payOrderId,
    displayMode: "qr_code",
    channelExtras: props.orderInfo
  })

  submitInfo.value = res;
  nextTick(()=>{
    initCanvas();
  })
}

onUnmounted(() => {
  clearInterval(timer);
})

const initCanvas = () => {
  const canvas = document.getElementById(ctxId.value);

  QRCode.toCanvas(
    canvas,
    submitInfo.value.displayContent||'',//props.content,
    {
      scale: 4, // 二维码的每个点的像素大小
      width: 150, // 在浏览器中显示的宽度
      margin: 1 // 二维码周围的空白边距
    }
  );
};


onMounted(() => {
  getQrCode();

  initTimer();


})

const generateInfo=()=>{
  let option = {
    orderInfo: props.orderInfo,
    selectedPackage:{
      ...props.selectedPackage,
      time:dayjs( submitInfo.value.successTime).format('YYYY-MM-DD HH:mm:ss'),
      type:1,
      method:method.value.find(at=>at.code == selectedMethod.value)?.name
    }
  }

  return option
}


watch(()=>selectedMethod.value,()=>{
  getQrCode();
})



watch(()=>app.payStatus,()=>{
  console.log(app.payStatus,"===============================watch")
  if(app.payStatus){
    sessionStorage.setItem('payInfo',JSON.stringify(generateInfo()))
    app.payStatus=false;
    router.push(`/fee/fee/paid`);
  }
},{
  immediate:true
})


</script>
<style lang="scss" scoped>

</style>
